package utils

import (
	"MoSkeleton/framework/core/consts"
	"MoSkeleton/framework/core/moerrors"
	"github.com/gin-gonic/gin"
	"mime"
	"mime/multipart"
	"path"
	"path/filepath"
	"regexp"
	"strings"
)

func PathMatches(pattern, urlPath string) bool {
	// 将模式中的任何变量替换为*以简化匹配
	pattern = removePathVariables(pattern)
	matched, err := path.Match(pattern, urlPath)
	if err != nil {
		return false
	}
	return matched
}

// 本系统只接受multipart/form-data的文件请求
func IsFileReuqest(c *gin.Context) bool {
	if !strings.Contains(c.GetHeader("Content-Type"), "multipart/form-data") {
		return false
	}
	return true
}

func GetFileExtension(file *multipart.FileHeader) (string, error) {
	ext := filepath.Ext(file.Filename)
	if ext == "" {
		contentTypes := file.Header["Content-Type"]
		if len(contentTypes) > 0 {
			mimeType, params, err := mime.ParseMediaType(contentTypes[0])
			if err == nil {
				if ext, ok := params["extension"]; ok {
					return ext, nil
				}
				exts, err := mime.ExtensionsByType(mimeType)
				if err != nil {
					return "", err
				}
				return exts[0], nil
			}
		}
		return "", moerrors.NewValidateError(consts.FilesUploadFailCode, "文件格式不正确")
	}
	return ext, nil
}

func removePathVariables(pattern string) string {
	// 使用正则表达式替换路径中的变量
	// 假设变量总是以冒号开始，例如/:variable
	regex := regexp.MustCompile(`/:.[^/]*`)
	return regex.ReplaceAllLiteralString(pattern, "/*")
}
